package com.yang.sso.oauth.oauth.exception;

import com.yang.sso.oauth.result.Result;
import com.yang.sso.oauth.enums.ResultCode;
import lombok.extern.slf4j.Slf4j;

import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.security.web.util.ThrowableAnalyzer;
import org.springframework.stereotype.Component;


/**
 * @Author lslands
 * @Version 1.0
 * @Date 2023/3/6 10:55
 * @PackageName:com.auth.boot.oauth2.exception
 * @ClassName: ResponseExceptionTranslator
 * @Description: 异常翻译处理器
 */
@Slf4j
@Component
public class ResponseExceptionTranslator implements WebResponseExceptionTranslator {

    private ThrowableAnalyzer throwableAnalyzer = new ThrowableAnalyzer();

    @Override
    public ResponseEntity translate(Exception e) throws Exception {
        //获取异常栈信息
        Throwable[] throwables = this.throwableAnalyzer.determineCauseChain(e);
        //获取AuthenticationException异常信息,不存在则返回的是null
        Exception ase = (AuthenticationException) this.throwableAnalyzer.getFirstThrowableOfType(AuthenticationException.class, throwables);
        if (ase != null) {
            log.error("身份验证异常:{}",ase.getMessage());
            return ResponseEntity.ok(Result.failed(ResultCode.ACCESS_UNAUTHORIZED));
        }
        //获取AccessDeniedException异常信息,不存在则返回的是null
        ase = (AccessDeniedException) this.throwableAnalyzer.getFirstThrowableOfType(AccessDeniedException.class, throwables);
        if (ase != null) {
            log.error("访问被拒绝异常:{}",ase.getMessage());
            return ResponseEntity.ok(ResultCode.ACCESS_UNAUTHORIZED);
        }
        //InvalidGrantException
        ase = (InvalidGrantException) throwableAnalyzer.getFirstThrowableOfType(InvalidGrantException.class, throwables);
        if (ase != null) {
            log.error("无效的授予异常:{}",ase.getMessage());
            return ResponseEntity.ok(Result.failed(ResultCode.ACCESS_UNAUTHORIZED));
        }
        log.error("授权类型异常:{}",e.getMessage());
        return ResponseEntity.ok(Result.failed(ResultCode.ACCESS_UNAUTHORIZED));
    }

}
